/**
 * SPDX-FileCopyrightText: 2023-2025 Sangfor Technologies Inc.
 * SPDX-License-Identifier: Mulan PSL v2
 */
<template>
    <div style="height: 100%;width: 100%">
        <sf-e-charts v-show="!isEmpty"
                ref="line"
                :options="lineOptions"
                :autoDestroy="false"
                :autoRefresh="true"></sf-e-charts>
        <empty-panel v-show="isEmpty"
                     :title="_('暂无数据')" />
    </div>
</template>

<script>
    import {
        encodeDate
    } from 'src/util/format';
    import { getYConfig, getDefaultTypeConfig, SUANLI_VALUE } from '../resource/const';
    import EmptyPanel from 'src/components/empty_panel.vue';

    import store from 'src/vuex/store';
    let userID = store.state.userId;
    const GPU_RATIO_URL = `auth/v1/user/${userID}/vGpuRatioUsageTrend`;
    const GPU_MEMORY_URL = `auth/v1/user/${userID}/vGpuMemoryUsageTrend`;
    const USER_URL = `auth/v1/user/resourceUsingGraph`;
    export default {
        components: {
            EmptyPanel
        },
        props: {
            forMat: {
              type: String,
              default: 'H:i'
            },
            use: {
                type: String,
                default: ''
            },
            type: {
                type: String
            },
            time: {
                type: String
            },
            areaColor: {
                type: String,
                default: '#F2EBFF'
            },
            lineColor: {
                type: String,
                default: '#5D1DFF'
            },
            gridPosition: {
                type: Object,
                default: () => {}
            },
            xShow: {
                type: Boolean,
                default: true
            }
        },
        inject: {
            lineChartDate: { default: () => {} }
        },
        data () {
            return {
                isEmpty: false,
                num: 0,
                lineOptions: {},
                xy_axis: [],
                lineChartsData: [],
                maxY: 0
            };
        },

        computed: {
            lineDate() {
                return this.lineChartDate && this.lineChartDate();
            }
        },

        watch: {
            lineChartsData: {
                deep: true,
                immediate: true,
                handler () {
                    this.resizeLine()
                }
            },
            type () {
                this.getLineData();
            },
            time () {
                this.getLineData();
            },
            lineDate () {
                this.getLineData();
            }
        },

        mounted () {
            this.getLineData();
        },

        methods: {
            async getLineData() {
                let url = '';

                let params = {
                    timeCode: this.time
                };
                if (this.use === 'user') {
                    params.trendChartType = this.type;
                    url = USER_URL
                } else {
                    url = this.type === SUANLI_VALUE ? GPU_RATIO_URL : GPU_MEMORY_URL;
                }
                let jsonData = await this.$ajax.get(url, params);
                if (!jsonData.success) {
                    this.updateIsEmpty(true);
                    return this.$showErr(jsonData.message || _('网络请求失败'));
                }
                if (jsonData?.data?.result.length) {
                    this.lineChartsData = jsonData?.data?.result.map(item => {
                        return {
                            x: item.x,
                            y: item.y
                        }
                    });

                    this._initLineChart();
                    this.updateIsEmpty(false);

                } else {
                    this.updateIsEmpty(true);
                }
            },

            updateIsEmpty (val) {
                this.isEmpty = val;
            },

            resizeLine () {
                this.handlerData();
                this.$nextTick().then(() => {
                    this._initLineChart();
                });
            },

            handlerData () {
                let vm = this;
                vm.xy_axis = [];

                this.maxY = Math.max(...this.lineChartsData.map(item => item.y));

                for (let i = 0; i < vm.lineChartsData.length; i++) {
                    let seriesItem = vm.lineChartsData[i];
                    vm.xy_axis.push([encodeDate(Number(seriesItem.x)), Number(seriesItem.y)])
                }
            },

            lineResize () {
                if (this.isEmpty) {
                    return;
                }
                this.$refs.line?.resize && this.$refs.line?.resize();
            },

            _initLineChart () {

                if (this.$refs.line) {
                    this.$refs.line.destroy();
                }

                let vm = this;
                this.lineOptions = {
                    grid: {
                        top: vm.gridPosition?.top || 40,
                        right: vm.gridPosition?.right || 80,
                        bottom: vm.gridPosition?.bottom || 40,
                        left: vm.gridPosition?.left || 80
                    },
                    title: {
                        textStyle: {
                            fontSize: '12px',
                            color: '#FFF',
                            fontFamily: 'Microsoft Yahei'
                        }
                    },
                    xAxis: {
                        type: 'time',
                        show: vm.xShow,
                        axisTick: {
                            show: false
                        },
                        axisLine: {
                            show: false
                        },
                        axisLabel: {
                            formatter: (val) => {
                                return encodeDate(val, vm.forMat);
                            }
                        },
                        splitLine: {
                            show: false
                        },
                        ...getDefaultTypeConfig(vm.time)
                    },
                    yAxis: {
                        type: 'value',
                        axisTick: { // y轴线刻度
                            show: false
                        },
                        axisLine: { // y轴线
                            show: false
                        },
                        axisLabel: {
                            color: '#999'
                        },
                        splitLine: {    // y轴分割线
                            show: true,
                            lineStyle: {
                                color: '#eee'
                            }
                        },
                        ...getYConfig(vm.type, {
                            yMax: vm.maxY
                        })
                    },
                    tooltip: {
                        trigger: 'axis',
                        transitionDuration: 0,
                        axisPointer: {
                            type: 'cross',
                            label: {
                                backgroundColor: vm.lineColor || '#1f4ed9',
                                fontSize: 12
                            }
                        },
                        backgroundColor: '#fff',
                        textStyle: {
                            fontSize: 12,
                            color: '#333'
                        }
                    },
                    series: [
                        {
                            type: 'line',
                            showSymbol: false,
                            data: vm.xy_axis,
                            areaStyle: {
                                color: vm.areaColor
                            }
                        }
                    ],
                    color: vm.lineColor
                }
            }
        }
    };
</script>
